package com.aliengen.thingple.driverapp.data.local;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import com.aliengen.thingple.driverapp.data.models.TruckTag;
import com.aliengen.thingple.driverapp.network.api.exception.FieldNotFoundException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;

/**
 * This class is part of the Thingple mobile application for the CMC168 Handheld reader.
 *
 * Copyright AlienGen Limited 2016. All rights reserved.
 *
 * @author Timothé Mermet-Buffet <tim@aliengen.com>
 */
@Table(name = "Truck")
public class TruckModel extends Model implements Serializable  {
    @Column(name = "truck_id",index = true,unique = true)
    public int truck_id;

    @Column(name = "truck_plate_number")
    public String plate_number;

    public TruckModel() {
        super();
    }

    public TruckModel(JSONObject json) throws FieldNotFoundException {
        super();
        if (!(json.has("truck_id") && json.has("truck_plate_number"))) {
            throw new FieldNotFoundException("Missing fields!");
        }

        try {
            this.truck_id = json.getInt("truck_id");
            this.plate_number = json.getString("truck_plate_number");
        } catch(JSONException e)
        {
            throw new FieldNotFoundException(e);
        }
    }

    public static TruckModel getTruck(TruckTag tag)
    {
        return new Select().from(TruckModel.class).where("truck_id = ?", tag.getTruckId()).executeSingle();
    }

    public int getTruckId() { return this.truck_id; }
    public String getPlateNumber() { return this.plate_number; }

    public static TruckModel getOrSet(JSONObject truck) throws FieldNotFoundException
    {
        if(!truck.has("truck_id"))
        {
            throw new FieldNotFoundException("Missing truck fields!");
        }

        try {
            TruckModel truck_object = new Select().from(TruckModel.class).where("truck_id = ?", truck.getInt("truck_id")).executeSingle();

            if(truck_object != null)
            {
                if(truck.has("truck_plate_number") && truck_object.plate_number.compareTo(truck.getString("truck_plate_number")) != 0)
                {
                    truck_object.plate_number = truck.getString("truck_plate_number");
                    truck_object.save();
                }
                return truck_object;
            }

            truck_object = new TruckModel(truck);
            truck_object.save();

            return truck_object;
        } catch(JSONException e) {
            throw new FieldNotFoundException(e.getMessage());
        }
    }
}
